/*
Copyright (c) 2008, Daniel Guerrero Martínez
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
	-Redistributions of source code must retain the above copyright notice, this
	list of conditions and the following disclaimer.
	-Redistributions in binary form must reproduce the above copyright notice,
	this list of conditions and the following disclaimer in the documentation
	and/or other materials provided with the distribution.
	-Neither the name of the <ORGANIZATION> nor the names of its contributors may
	be used to endorse or promote products derived from this software without
	specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
 */


package Imagenes;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.RescaleOp;
import java.awt.image.ShortLookupTable;


public class Filtros extends javax.swing.JDialog {


    public Filtros(java.awt.Frame parent, boolean modal,java.awt.image.BufferedImage I) {
        super(parent, modal);
        initComponents();
       
        base = new BufferedImage(
                   I.getWidth(),I.getHeight(),
                   BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = base.createGraphics();
        g2d.drawImage(I, 0, 0, null);
        original = I;
        filtrada = new java.awt.image.BufferedImage(original.getWidth(), original.getHeight(), java.awt.image.BufferedImage.TYPE_INT_RGB);
        filtrada.getGraphics().drawImage(original, 0, 0,null);

        mascaras[0] = filtroMedia;
        mascaras[1] = filtroBinomial;
        mascaras[2] = filtroRealce;
        mascaras[3] = filtroLaplaciano;
        id_mascara = -1;

        this.B_ninguna_mascara.addActionListener(new CambioMascara(-1));
        this.B_Filtro_media.addActionListener(new CambioMascara(0));
        this.B_Filtro_binomial.addActionListener(new CambioMascara(1));
        this.B_contrornos.addActionListener(new CambioMascara(3));
        this.B_negativo.addActionListener(new CambioMascara(4));
        this.B_logaritmico.addActionListener(new CambioMascara(5));
        this.B_gamma.addActionListener(new CambioMascara(6));
        
        double f=0,f2=0;
        double K1 = 255.0/Math.log(256.0);
        double K2 = 255.0/Math.pow(255.0,0.40);
        double K3 = 255.0 / (   1.0 / (  1.0  +  Math.pow( 128.0/256.0 , 2.0)));
        for (int j=0; j<256; j++) {
             lt[0][j] = (short)(256-j-1); // Negativo
             lt[1][j] = (byte)(K1*Math.log(1.0+(double)j)); // Logaritmo
             lt[2][j] = (byte)(K2*Math.pow((double)j,0.40));// Gamma
             if(j==0) lt[3][j]=0;
             else {
               f = 1.0 / (1.0 + Math.pow(128.0 / (float) j, 2.0));  // Contraste
               lt[3][j] = (short)(K3*f);
             }
        }

    }


    @Override
    public void paint(Graphics G){
        super.paint(G);
        P_filtrado.getGraphics().drawImage(filtrada, 0, 0,P_filtrado.getWidth(),P_filtrado.getHeight(), P_filtrado);
        P_original.getGraphics().drawImage(base, 0, 0,P_original.getWidth(),P_original.getHeight(), P_original);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        Grupo_marcaras = new javax.swing.ButtonGroup();
        Previsualizacion = new javax.swing.JPanel();
        P_original = new javax.swing.JPanel();
        P_filtrado = new javax.swing.JPanel();
        E_original = new javax.swing.JLabel();
        E_filtrado = new javax.swing.JLabel();
        Filtros = new javax.swing.JTabbedPane();
        Brillo = new javax.swing.JPanel();
        E_brillo = new javax.swing.JLabel();
        B_brillo = new javax.swing.JSlider();
        E_contraste = new javax.swing.JLabel();
        B_contrste = new javax.swing.JSlider();
        B_blanconegro = new javax.swing.JCheckBox();
        Mascaras = new javax.swing.JPanel();
        B_ninguna_mascara = new javax.swing.JRadioButton();
        B_Filtro_media = new javax.swing.JRadioButton();
        B_Filtro_binomial = new javax.swing.JRadioButton();
        B_contrornos = new javax.swing.JRadioButton();
        B_negativo = new javax.swing.JRadioButton();
        B_logaritmico = new javax.swing.JRadioButton();
        B_gamma = new javax.swing.JRadioButton();
        B_aplicar = new javax.swing.JButton();
        B_cancelar = new javax.swing.JButton();
        B_aceptar = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(600, 550));
        setResizable(false);
        getContentPane().setLayout(null);

        Previsualizacion.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        P_original.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        javax.swing.GroupLayout P_originalLayout = new javax.swing.GroupLayout(P_original);
        P_original.setLayout(P_originalLayout);
        P_originalLayout.setHorizontalGroup(
            P_originalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 264, Short.MAX_VALUE)
        );
        P_originalLayout.setVerticalGroup(
            P_originalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 204, Short.MAX_VALUE)
        );

        Previsualizacion.add(P_original, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 270, 210));

        P_filtrado.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        javax.swing.GroupLayout P_filtradoLayout = new javax.swing.GroupLayout(P_filtrado);
        P_filtrado.setLayout(P_filtradoLayout);
        P_filtradoLayout.setHorizontalGroup(
            P_filtradoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 264, Short.MAX_VALUE)
        );
        P_filtradoLayout.setVerticalGroup(
            P_filtradoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 204, Short.MAX_VALUE)
        );

        Previsualizacion.add(P_filtrado, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 30, 270, 210));

        E_original.setText("Original");
        Previsualizacion.add(E_original, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 270, -1));

        E_filtrado.setText("Filtrado");
        Previsualizacion.add(E_filtrado, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 10, 270, -1));

        getContentPane().add(Previsualizacion);
        Previsualizacion.setBounds(0, 0, 580, 250);

        Brillo.setLayout(null);

        E_brillo.setText("Brillo");
        Brillo.add(E_brillo);
        E_brillo.setBounds(10, 10, 40, 40);

        B_brillo.setMaximum(255);
        B_brillo.setMinimum(-255);
        B_brillo.setPaintLabels(true);
        B_brillo.setPaintTrack(false);
        B_brillo.setValue(0);
        B_brillo.addChangeListener(formListener);
        Brillo.add(B_brillo);
        B_brillo.setBounds(90, 0, 200, 50);

        E_contraste.setText("Contraste");
        Brillo.add(E_contraste);
        E_contraste.setBounds(10, 80, 50, 30);

        B_contrste.setMaximum(10);
        B_contrste.setPaintLabels(true);
        B_contrste.setPaintTrack(false);
        B_contrste.setValue(0);
        B_contrste.addChangeListener(formListener);
        Brillo.add(B_contrste);
        B_contrste.setBounds(90, 60, 200, 60);

        B_blanconegro.setText("Escala de grises");
        B_blanconegro.addActionListener(formListener);
        Brillo.add(B_blanconegro);
        B_blanconegro.setBounds(340, 20, 210, 23);

        Filtros.addTab("Brillo y contraste", Brillo);

        Mascaras.setLayout(null);

        Grupo_marcaras.add(B_ninguna_mascara);
        B_ninguna_mascara.setSelected(true);
        B_ninguna_mascara.setText("Ninguna");
        Mascaras.add(B_ninguna_mascara);
        B_ninguna_mascara.setBounds(20, 20, 140, 23);

        Grupo_marcaras.add(B_Filtro_media);
        B_Filtro_media.setText("Suavizado media");
        Mascaras.add(B_Filtro_media);
        B_Filtro_media.setBounds(20, 50, 170, 23);

        Grupo_marcaras.add(B_Filtro_binomial);
        B_Filtro_binomial.setText("Suavizado logaritmico");
        Mascaras.add(B_Filtro_binomial);
        B_Filtro_binomial.setBounds(20, 80, 170, 23);

        Grupo_marcaras.add(B_contrornos);
        B_contrornos.setText("Contornos");
        Mascaras.add(B_contrornos);
        B_contrornos.setBounds(20, 110, 170, 23);

        Grupo_marcaras.add(B_negativo);
        B_negativo.setText("Negativo");
        Mascaras.add(B_negativo);
        B_negativo.setBounds(200, 20, 130, 23);

        Grupo_marcaras.add(B_logaritmico);
        B_logaritmico.setText("Logaritmico");
        Mascaras.add(B_logaritmico);
        B_logaritmico.setBounds(200, 50, 130, 23);

        Grupo_marcaras.add(B_gamma);
        B_gamma.setText("Gamma");
        Mascaras.add(B_gamma);
        B_gamma.setBounds(200, 80, 130, 23);

        Filtros.addTab("Filtros", Mascaras);

        getContentPane().add(Filtros);
        Filtros.setBounds(0, 250, 580, 210);

        B_aplicar.setText("Aplicar");
        B_aplicar.addActionListener(formListener);
        getContentPane().add(B_aplicar);
        B_aplicar.setBounds(180, 470, 120, 23);

        B_cancelar.setText("Cancelar");
        B_cancelar.addActionListener(formListener);
        getContentPane().add(B_cancelar);
        B_cancelar.setBounds(440, 470, 120, 23);

        B_aceptar.setText("Aceptar");
        B_aceptar.addActionListener(formListener);
        getContentPane().add(B_aceptar);
        B_aceptar.setBounds(310, 470, 120, 23);

        pack();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, javax.swing.event.ChangeListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == B_blanconegro) {
                Filtros.this.BlancoYnegro(evt);
            }
            else if (evt.getSource() == B_aplicar) {
                Filtros.this.aplicar_filtros(evt);
            }
            else if (evt.getSource() == B_cancelar) {
                Filtros.this.cancelar(evt);
            }
            else if (evt.getSource() == B_aceptar) {
                Filtros.this.Aceptar(evt);
            }
        }

        public void stateChanged(javax.swing.event.ChangeEvent evt) {
            if (evt.getSource() == B_brillo) {
                Filtros.this.AplicarFiltro(evt);
            }
            else if (evt.getSource() == B_contrste) {
                Filtros.this.contrste_AplicarFiltro(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    private void aplicar_filtros(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aplicar_filtros
        base.getGraphics().drawImage(filtrada, 0, 0,null);
        this.repaint();
    }//GEN-LAST:event_aplicar_filtros

    private void cancelar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelar
        this.setVisible(false);
    }//GEN-LAST:event_cancelar

    private void AplicarFiltro(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_AplicarFiltro

        if(id_mascara > -1 && id_mascara < 4){
            Kernel k = new Kernel(3,3,mascaras[id_mascara]);
            ConvolveOp cop = new ConvolveOp( k );
            cop.filter(base,filtrada);
        }else if(id_mascara >4 ){
            ShortLookupTable slt = new ShortLookupTable(0, lt[id_mascara-4]);
            LookupOp lop = new LookupOp(slt, null);
            lop.filter( base , filtrada);
        }else filtrada.getGraphics().drawImage(base, 0,0, null);

        for(int i = 0; i<this.B_contrste.getValue();i++){
            ShortLookupTable slt = new ShortLookupTable(0, lt[3]);
            LookupOp lop = new LookupOp(slt, null);
            lop.filter( filtrada , filtrada);
        }

        RescaleOp rop = new RescaleOp(1,B_brillo.getValue(),null);
        filtrada = rop.filter(filtrada,null);

        if(this.B_blanconegro.isSelected()){
            ICC_Profile ip = ICC_Profile.getInstance(ColorSpace.CS_GRAY);
            ColorSpace cs = new ICC_ColorSpace(ip);
            ColorConvertOp ccop = new ColorConvertOp(cs,null);
            ccop.filter(filtrada,filtrada);

        }

        P_filtrado.getGraphics().drawImage(filtrada, 0, 0,P_filtrado.getWidth(),P_filtrado.getHeight(), P_filtrado);
    }//GEN-LAST:event_AplicarFiltro

    private void contrste_AplicarFiltro(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_contrste_AplicarFiltro
        AplicarFiltro(evt);
}//GEN-LAST:event_contrste_AplicarFiltro

    private void Aceptar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Aceptar
        this.setVisible(false);
        original.getGraphics().drawImage(filtrada, 0, 0,null);
}//GEN-LAST:event_Aceptar

    private void BlancoYnegro(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BlancoYnegro
        AplicarFiltro(new javax.swing.event.ChangeEvent(evt));
    }//GEN-LAST:event_BlancoYnegro

private class CambioMascara implements java.awt.event.ActionListener{
        int identificador;

        CambioMascara(int ident){
            identificador = ident;
        }

        public void actionPerformed(ActionEvent e) {
            id_mascara = identificador;
            AplicarFiltro (new javax.swing.event.ChangeEvent(e));
        }
}


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton B_Filtro_binomial;
    private javax.swing.JRadioButton B_Filtro_media;
    private javax.swing.JButton B_aceptar;
    private javax.swing.JButton B_aplicar;
    private javax.swing.JCheckBox B_blanconegro;
    private javax.swing.JSlider B_brillo;
    private javax.swing.JButton B_cancelar;
    private javax.swing.JRadioButton B_contrornos;
    private javax.swing.JSlider B_contrste;
    private javax.swing.JRadioButton B_gamma;
    private javax.swing.JRadioButton B_logaritmico;
    private javax.swing.JRadioButton B_negativo;
    private javax.swing.JRadioButton B_ninguna_mascara;
    private javax.swing.JPanel Brillo;
    private javax.swing.JLabel E_brillo;
    private javax.swing.JLabel E_contraste;
    private javax.swing.JLabel E_filtrado;
    private javax.swing.JLabel E_original;
    private javax.swing.JTabbedPane Filtros;
    private javax.swing.ButtonGroup Grupo_marcaras;
    private javax.swing.JPanel Mascaras;
    private javax.swing.JPanel P_filtrado;
    private javax.swing.JPanel P_original;
    private javax.swing.JPanel Previsualizacion;
    // End of variables declaration//GEN-END:variables
    private java.awt.image.BufferedImage original;
    private java.awt.image.BufferedImage base;
    private java.awt.image.BufferedImage filtrada;
    private float mascaras[][]={{},{},{},{}} ;
    private int id_mascara;
    float filtroMedia[] = {
                  0.1f, 0.1f, 0.1f,
                  0.1f, 0.2f, 0.1f,
                  0.1f, 0.1f, 0.1f
                 };
    float filtroBinomial[] = {
                 0.0625f, 0.125f, 0.0625f,
                 0.125f, 0.25f, 0.125f,
                 0.0625f, 0.125f, 0.0625f
                 };
    float filtroRealce[] = {
                  0.0f, -1.0f, 0.0f,
                 -1.0f,  5.0f, -1.0f,
                  0.0f, -1.0f, 0.0f
                 };
    float filtroLaplaciano[] = {
                  1.0f, 1.0f,  1.0f,
                  1.0f, -8.0f, 1.0f,
                  1.0f, 1.0f,  1.0f
                  };
    short lt[][] = new short[4][256];


}
